package com.fms.fmsapi.utils;

import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.Map;

public class FetchGet<T> {

    RestTemplate restTemplate = new RestTemplate();
    //请求路径
    private String url;
    // 请求参数
    private String accessToken;
    // 设置请求头
    private HttpHeaders headers = new HttpHeaders();
    // 设置请求参数
    private MultiValueMap<String,String> queryParams;

    public FetchGet() {
        //设置默认的请求头为 text/pain
        this.headers.setContentType(MediaType.TEXT_PLAIN);
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getAccessToken() {
        return accessToken;
    }
    //会自动将token加入请求体中
    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    public HttpHeaders getHeaders() {
        return headers;
    }

    public void setHeaders(Map<String,String> headers) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            this.headers.set(entry.getKey(),entry.getValue());
        }
    }

    public MultiValueMap<String,String> getQueryParams() {
        return queryParams;
    }

    public void setQueryParams(MultiValueMap<String,String> queryParams) {
        this.queryParams = queryParams;
    }

    /**
     * 需要指定返回的类型
     * @param resultClass
     */
    public T fetch(Class<T> resultClass){

        //拼接上url
        URI url = UriComponentsBuilder.fromUriString(this.url)
                .queryParams(this.queryParams)
                .build()
                .toUri();
        // 创建请求实体
        HttpEntity<String> request = new HttpEntity<>(headers);
        // 发送POST请求
        ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET, request, resultClass);
        return response.getBody();
    }
}
